import { TabBar, Toast } from "antd-mobile";
import { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { home, addCart } from '../../api/home'

// 个人信息背景图片
import minebg from "../../assets/mybgimg.png";
import "./mine.css";
// 头像
import head from "../../assets/head.jpg";
// 订单箭头
import arrow from "../../assets/arrowRight.png";
// 待付款
import obligation from "../../assets/obligation.png";
// 待收货
import waitRece from "../../assets/waitRece.png";
// 待评价
import evaluate from "../../assets/evaluate.png";
// 已完成
import accomplish from "../../assets/accomplish.png";
// 退换货
import Changing from "../../assets/Changing.png";
// 我的钱包
import wallet from "../../assets/wallet.png";
// 分销中心
import centre from "../../assets/centre.png";
// 收货地址
import localicon from "../../assets/localicon.png";
// 邀请好友
import inviteicon from "../../assets/inviteicon.png";
// 猜你喜欢左右爱心图标
import loveLeft from "../../assets/leftlove.png";
import loveRight from "../../assets/lovelike.png";

// 添加购物车图标
import add from '../../assets/add.png'
// 添加成功图标
import ok from '../../assets/ok.png'

import {
  AppOutline,
  MessageOutline,
  UnorderedListOutline,
  UserOutline,
} from "antd-mobile-icons";

let url = "http://jingxun.kuxia.top";

export default function Mine() {
  const navigate = useNavigate();
  const location = useLocation();

  const tabs = [
    {
      key: "/home",
      title: "首页",
      icon: <AppOutline />,
    },
    {
      key: "/todo",
      title: "分类",
      icon: <UnorderedListOutline />,
    },
    {
      key: "/shopping",
      title: "购物车",
      icon: <MessageOutline />,
    },
    {
      key: "/mine",
      title: "我的",
      icon: <UserOutline />,
    },
  ];

  const [activeKey, setActiveKey] = useState(location.pathname);
  // 添加推荐商品数据状态
  const [recommendItems, setRecommendItems] = useState([]);
  // 添加购物车商品状态
  const [cartItems, setCartItems] = useState({});

  useEffect(() => {
    setActiveKey(location.pathname);
  }, [location.pathname]);

  // 获取推荐商品数据
  useEffect(() => {
    const fetchRecommendData = async () => {
      try {
        const response = await home();
        if (response && response.data && response.data.commodity) {
          setRecommendItems(response.data.commodity);
        }
      } catch (error) {
        console.error('获取推荐商品数据失败:', error);
      }
    };
    
    fetchRecommendData();
  }, []);

  const setRouteActive = (key) => {
    setActiveKey(key);
    navigate(key);
  };

  // 添加商品到购物车
  const handleAddToCart = async (commodityId) => {
    try {
      // 从本地存储获取用户信息
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
      const userId = userInfo.id;
      
      if (!userId) {
        Toast.show({
          content: '请先登录',
          position: 'top'
        });
        return;
      }
      
      // 调用添加购物车接口
      const response = await addCart({
        user_id: userId,
        commodity_id: commodityId,
        num: "1"
      });
      
      if (response.code === 1) {
        // 更新购物车状态
        setCartItems(prev => ({
          ...prev,
          [commodityId]: true
        }));
        
        Toast.show({
          content: '添加成功',
          position: 'top'
        });
      } else {
        Toast.show({
          content: '添加失败',
          position: 'top'
        });
      }
    } catch (error) {
      Toast.show({
        content: '添加失败',
        position: 'top'
      });
      console.error('添加购物车失败:', error);
    }
  };

  // 将商品数据分为两列（瀑布流）
  const renderWaterfall = () => {
    const leftColumn = [];
    const rightColumn = [];

    recommendItems.forEach((item, index) => {
      if (index % 2 === 0) {
        leftColumn.push(item);
      } else {
        rightColumn.push(item);
      }
    });

    return { leftColumn, rightColumn };
  };

  const { leftColumn, rightColumn } = renderWaterfall();

  return (
    <div style={{ height: "100vh", width: "100%", backgroundColor: "#F8F8F8" }}>
      <div className="mine-messge">
        <img src={minebg} alt=""></img>
        <div className="mine-message-text">
          <img src={head} alt="用户头像" />
          <div className="mine-message-text-text">
            <span>好青崧</span>
            <p>ID:1001466</p>
          </div>
        </div>
        <div className="earnings-box">
          <div className="earnings-items">
            <div className="earnings-item-text">
              <p>￥1243.23</p>
              <span>余额（元）</span>
            </div>
            <div className="earnings-item-text">
              <p>￥3341</p>
              <span>总收益（元）</span>
            </div>
            <div className="earnings-item-text">
              <p>￥741</p>
              <span>可用收益（元）</span>
            </div>
          </div>
        </div>
      </div>

      <div className="order-box">
        <div className="order-title">
          <p>我的订单</p>
          <span onClick={() => navigate("/order")}>
            全部订单
            <img src={arrow} alt=""></img>
          </span>
        </div>
        <div className="order-item">
          <div className="order-item-text">
            <img src={obligation} alt="" />
            <p>待付款</p>
          </div>
          <div className="order-item-text">
            <img src={waitRece} alt="" />
            <p>待收货</p>
          </div>
          <div className="order-item-text">
            <img src={evaluate} alt="" />
            <p>待评价</p>
          </div>
          <div className="order-item-text">
            <img src={accomplish} alt="" />
            <p>已完成</p>
          </div>
          <div className="order-item-text">
            <img src={Changing} alt="" />
            <p>退换货</p>
          </div>
        </div>
      </div>

      {/* 我的服务 */}
      <div className="service-box">
        <div className="service-title">
          <p>我的服务</p>
        </div>
        <div className="service-item">
          <div className="service-item-text">
            <img src={wallet} alt="" />
            <p>我的钱包</p>
          </div>
          <div className="service-item-text">
            <img src={centre} alt="" />
            <p>分销中心</p>
          </div>
          <div className="service-item-text">
            <img src={localicon} alt="" />
            <p>收货地址</p>
          </div>
          <div className="service-item-text">
            <img src={inviteicon} alt="" />
            <p>邀请好友</p>
          </div>
        </div>
      </div>

      {/* 猜你喜欢 */}
      <div className="cartRank-box">
        <div className="cartRank-title">
          <img src={loveLeft} alt="" />
          <span>猜你喜欢</span>
          <img src={loveRight} alt="" />
        </div>

        {/* 瀑布流商品列表 */}
        <div className="waterfall-container">
          <div className="waterfall-column">
            {leftColumn.map((item, index) => (
              <div 
                className="waterfall-item" 
                key={`left-${index}`}
                onClick={() => navigate(`/goods/${item.id}`)}
              >
                <img src={url + item.image} alt={item.title} />
                <p className="waterfall-item-title">{item.title}</p>
                <p className="waterfall-item-price">¥{item.price}</p>
                <img 
                  src={cartItems[item.id] ? ok : add} 
                  alt={cartItems[item.id] ? "已添加" : "添加到购物车"}
                  className="add-to-cart-icon"
                  style={{ width: '20px', height: '20px', position: 'absolute', right: '10px', bottom: '9px' }}
                  onClick={(e) => {
                    e.stopPropagation();
                    handleAddToCart(item.id);
                  }}
                />
              </div>
            ))}
          </div>
          <div className="waterfall-column">
            {rightColumn.map((item, index) => (
              <div 
                className="waterfall-item" 
                key={`right-${index}`}
                onClick={() => navigate(`/goods/${item.id}`)}
              >
                <img src={url + item.image} alt={item.title} />
                <p className="waterfall-item-title">{item.title}</p>
                <p className="waterfall-item-price">¥{item.price}</p>
                <img 
                  src={cartItems[item.id] ? ok : add} 
                  alt={cartItems[item.id] ? "已添加" : "添加到购物车"}
                  className="add-to-cart-icon"
                  style={{ width: '20px', height: '20px', position: 'absolute', right: '10px', bottom: '9px' }}
                  onClick={(e) => {
                    e.stopPropagation();
                    handleAddToCart(item.id);
                  }}
                />
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* 底部导航栏 */}
      <div
        style={{
          position: "fixed",
          bottom: 0,
          width: "100%",
          backgroundColor: "#ffffff",
        }}
      >
        <TabBar activeKey={activeKey} onChange={setRouteActive}>
          {tabs.map((item) => (
            <TabBar.Item key={item.key} icon={item.icon} title={item.title} />
          ))}
        </TabBar>
      </div>
    </div>
  );
}